<template>

<!--  <div style="background-color: #030303; margin-top: 60px">-->
<!--    <p style="font-size: 20px; color: #fff; text-align: center;">施工中</p>-->
<!--  </div>-->

  <div id="app">
    <div class="chat-header">AI对话</div>
    <el-tabs tab-position="left" type="border-card" closable @tab-remove="handleTabsEdit" style="height: 540px;">
      <el-tab-pane v-for="item in tagList" :label="item.title.length > 10? item.title.slice(0, 10) + '...' : item.title">
        <div class="chat-messages" ref="chatMessages" @click="getRecordListData">
          <div v-for="(message, index) in res.messages" :key="index"
              :class="{ 'user-message-div': message.from === '0', 'bot-message-div': message.from === '1' }">
            <div
                :class="{ 'message': true, 'user-message': message.from === '0', 'bot-message': message.from === '1' }">
              <p class="message-text" v-for="item,index in textToCode(message.text)" :key="item">
                <span v-if="index%2 == 0"> {{ item }} </span>
                <pre v-else><code class="prism-code " :class="[`language-${item.split('\n', 2)[0]}`]">{{ item.split('\n').slice(1).join('\n')}}</code></pre>
              </p>
            </div>
          </div>
          <a ref="autoFocus">~</a>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <div class="input-container">
      <input type="text" class="message-input" v-model="res.userInput" @keyup.enter="sendMessage">
      <button class="send-button" @click="sendMessage">Send</button>
    </div>

  </div>

</template>

<script setup lang="ts">
import {fetchData, getRecordList, getTagList} from "@/api/aiChat";
import {ElNotification} from "element-plus";
import {PageQuery} from "@/model";
import Prism from "prismjs";



const data = reactive({
  count: 0,
  queryParams: {
    pageNo: 1,
    pageSize: 60,
  } as PageQuery,
});
const {queryParams} = toRefs(data);

interface Message {
  userInput: string;
  messages: message[];
}

interface message {
  from: string;
  text: string;
}

const res = reactive<Message>({
  userInput: '',
  messages: []
})


const autoFocus = ref();
const tagList =ref<{title: string}[]>([]);


onMounted(async () => {



  
  // 延时渲染代码块
  setTimeout(() => {
    Prism.highlightAll()
    
  }, 1000)


  await  getTagList(queryParams.value).then((data: any) => {
    let result = data.data;
    if (result.code == 200) {
      let lists = result.data.lists;
      tagList.value = lists;
    } else {
      ElNotification({
        title: 'Error',
        message: "请先登录",
        type: 'error',
      })
    }


  });

})


const getRecordListData =  getRecordList(queryParams.value).then((data: any) => {
  let result = data.data;
  if (result.code == 200) {
    let lists = result.data.lists;
    lists.forEach((item: any) => {

      res.messages.unshift({
        from: item.type + "",
        text: item.content
      })
    })
    // 滚动到底部
    nextTick(() => {
      autoFocus.value.scrollIntoView({behavior: "smooth"})
    })

  } else {
    ElNotification({
      title: 'Error',
      message: "请先登录",
      type: 'error',
    })
  }


});

const sendMessage = () => {
  if (res.userInput.trim() === '') {
    return;
  } else {
    res.messages.push({
      from: '0',
      text: res.userInput
    })
    let fromData: message = {
      from: '1',
      text: ""
    }
    res.messages.push(fromData)
    fetchData(res.userInput, (dataChunk) => {
      res.messages[res.messages.length - 1].text += dataChunk

      // 接受完消息执行代码高亮
      Prism.highlightAll()

      // 滚动
      autoFocus.value.scrollIntoView({behavior: "smooth"})
    }).then(() => {
      
    })
  }

}

function textToCode(text: string) {
  try {
      // return text.replace(/```.*?```/g, (str) => {
      //   str = str.slice(3, str.length - 3)
      //   let arr = str.split(' ')
      //   return `<pre>
      //       <code class="prism-code language-${arr[0]}">
      //         ${arr[1]}
      //       </code>
      //     </pre>`
      // })
      return text.split('```')
  } catch (e) {
    return text
  }
}

function handleTabsEdit() {
  
}

</script>

<style scoped>

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  background-color: #f4f4f4;
}

#app {
  min-width: 600px;
  width: 100vw;
  margin: 50px auto;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

.user-message-div {
  display: flex;
  flex-direction: row-reverse;
}

.bot-message-div {
  display: flex;
}

.chat-header {
  background-color: #3388dc;
  color: #fff;
  padding: 10px;
  text-align: center;
  font-size: 18px;
}

.chat-messages {
  min-height: 300px;
  padding: 15px;
  overflow-y: auto;
  max-height: 600px;
}

.message {
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 8px;

}

.user-message {
  background-color: #DCF8C6;
  align-self: flex-start;
  /*width: min-content;*/

}

.bot-message {
  background-color: #C6E2FF;
  align-self: flex-end;
  /*width: min-content;*/
}

.message.user-message.message-text {
  float: left;
}

.message-text {
  margin: 0;

}

.input-container {
  display: flex;
  padding: 15px;
  background-color: #f0f0f0;
}

.message-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

.send-button {
  padding: 10px 20px;
  background-color: #248cb2;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>